import { sysLoginRequest, sysProfileRequest } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'
import router from '@/router/index'
import { Message } from 'element-ui'
export default {
  namespaced: 'user',
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  actions: {
    // 发送请求获取token
    async loginAction(context, payload) {
      try {
        const data = await sysLoginRequest(payload)
        Message.success('登录成功')
        context.commit('setTokenMutation', data.data)
      } catch (error) {
        console.log(error)
      }
    },
    // 发送请求获取个人信息
    async getProfileAction(context) {
      try {
        const res = await sysProfileRequest()
        context.commit('setProfileMutation', res.data)
      } catch (error) {
        console.log(error)
      }
    },
    // token过期/退出登录
    logoutAction(context) {
      context.commit('setTokenMutation', '')
      context.commit('setProfileMutation', {})
      router.replace('/login')
      Message.success('退出成功')
    }
  },
  mutations: {
    // 存储token到cookie
    setTokenMutation(state, payload) {
      setToken(payload)
      state.token = payload
    },
    // 存储用户信息
    setProfileMutation(state, payload) {
      state.userInfo = payload
    }
  }
}
